<template>
  <div class="shopcar">
    <topNav
      ><slot>购物车 ({{ carData.length }})</slot>
    </topNav>
    <div v-if="carData == ''" class="shop">购物车为空</div>

    <div class="shop" v-else>
      <div class="carbox" v-for="item in carData" :key="item.id">
        <!-- <p>{{item.id}}</p> -->
        <input
          type="checkbox"
          :checked="item.check"
          @change.stop="getChecked(item.id, $event)"
        />
        <img :src="item.img" />
        <div class="center">
          <h4>{{ item.title }}</h4>
          <p>{{ item.title }}</p>
          <div class="cen">
            <p>￥{{ item.price }}</p>
            <span>x1</span>
          </div>
        </div>
      </div>
    </div>
    <div>
      <input type="checkbox" @change="checkAllHandle" v-model="checkAll" />全选
      <span>总价 {{ carData | filterPrice }} 元</span>
    </div>
    <buttonNav></buttonNav>
  </div>
</template>

<script>
import ButtonNav from "../components/buttonNav.vue";
import topNav from "../components/topNav.vue";
export default {
  components: { topNav, ButtonNav },
  name: "Shopcar",
  data() {
    return {
      carData: this.$store.state.carData,
      checkAll: false,
      allPrice: "",
    };
  },
  mounted() {},
  methods: {
    getChecked(id, e) {
      console.log(e.target.checked);
      this.carData.forEach((v) => {
        v.id === id ? (v.check = e.target.checked) : "";
        this.checkAll = this.carData.every((v) => v.check);
      });
    },
    checkAllHandle() {
      this.carData.forEach((item) => {
        item.check = this.checkAll;
        console.log(item.check);
      });
    },
  },
  filters: {
    filterPrice(arr) {


      if(!arr|| !arr.length){
        return 0
      }else{
        let num=0
        arr.forEach(item=>{
            if(item.check==true){
               num+= item.price*item.num
            }
        })
        return num
      }

     
    },
  },
};
</script>

<style lang="scss" scoped>
.shop {
  margin-top: 50px;

  .carbox {
    width: 100%;
    height: 100px;
    border-bottom: 1px solid #ccc;
    display: flex;
    align-items: center;
    align-content: center;
    img {
      width: 20%;
      height: 80px;
    }
    .center {
      width: 70%;
      height: 100%;
      p,
      h4 {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      p {
        margin: 10px 0;
        font-size: 13px;
      }
      .cen {
        // margin: 15px 0;
        display: flex;
        justify-content: space-between;
        p {
          font-size: 20px;
          color: red;
        }
        span {
          font-weight: 700;
        }
      }
    }
  }
}
</style>